In [1]:
%matplotlib inline
In [2]:
import warnings
warnings.simplefilter('ignore')

What's new in Nilearn

Nilearn can do many things. We arbitrarily picked a few for this 5-minute demo. Check out the documentation (https://nilearn.github.io/user_guide.html) and the example gallery (https://nilearn.github.io/auto_examples/index.html) for more!

Interactive image vizualization: brain volume and cortical surface

In [3]:
# Download and plot a group-level statistical map:
from nilearn import datasets

img = datasets.fetch_neurovault_motor_task()['images'][0]
print(img)
/home/jerome/workspace/scikit-learn/sklearn/externals/joblib/__init__.py:15: DeprecationWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when loading pickled models, you may need to re-serialize those models with scikit-learn 0.21+.
  warnings.warn(msg, category=DeprecationWarning)
/home/jerome/nilearn_data/neurovault/collection_658/image_10426.nii.gz
In [4]:
from nilearn import plotting

plotting.view_img(img, threshold='95%')
Out[4]:

Made with the brainsprite viewer: https://github.com/SIMEXP/brainsprite.js

In [5]:
view = plotting.view_img(img, threshold='95%')
view.open_in_browser()

Static plots (matplotlib figures)

In [7]:
plotting.plot_stat_map(
    img, threshold=3, display_mode='z', cut_coords=[-20,64])
Out[7]:
<nilearn.plotting.displays.ZSlicer at 0x7fc209e168d0>

Projections on the cortical surface

In [8]:
plotting.view_img_on_surf(img, threshold='95%')
Out[8]:
In [9]:
plotting.view_img_on_surf(img, threshold='95%', surf_mesh='fsaverage')
Out[9]:

Easily creating connectivity matrices

we use one subject from a dataset recently added to Nilearn: a movie watching based brain development dataset

In [10]:
rest_data = datasets.fetch_development_fmri(n_subjects=60)
rest_data.keys()
Out[10]:
dict_keys(['func', 'confounds', 'phenotypic', 'description'])

Extract time series from probabilistic ROIs of the MSDL atlas.

In [11]:
from nilearn.input_data import NiftiMapsMasker
import numpy as np

msdl = datasets.fetch_atlas_msdl()
print('number of regions in MSDL atlas:', len(msdl.labels))

masker = NiftiMapsMasker(
    msdl.maps, resampling_target="data", t_r=2, detrend=True,
    low_pass=.1, high_pass=.01, memory='nilearn_cache', memory_level=3).fit([])
masked_data = [masker.transform(func, confounds) for
               (func, confounds) in zip(rest_data.func, rest_data.confounds)]
masked_data = np.asarray(masked_data)
print('masked data shape:', masked_data[0].shape)
number of regions in MSDL atlas: 39
masked data shape: (168, 39)

Compute and plot connectivity matrix

In [12]:
from nilearn.connectome import ConnectivityMeasure

correlation_measure = ConnectivityMeasure(kind='correlation').fit(masked_data)

plotting.plot_matrix(correlation_measure.mean_, tri='lower')
Out[12]:
<matplotlib.image.AxesImage at 0x7fc209c35080>
In [13]:
plotting.view_connectome(
    correlation_measure.mean_, msdl.region_coords,
    threshold='90%', cmap='cold_hot')
/home/jerome/.virtualenvs/py3.7/lib/python3.7/site-packages/ipykernel_launcher.py:3: DeprecationWarning: The parameter "threshold" will be removed in 0.6.0 release of Nilearn. Please use the parameter "edge_threshold" instead.
  This is separate from the ipykernel package so we can avoid doing imports until
/home/jerome/.virtualenvs/py3.7/lib/python3.7/site-packages/ipykernel_launcher.py:3: DeprecationWarning: The parameter "cmap" will be removed in 0.6.0 release of Nilearn. Please use the parameter "edge_cmap" instead.
  This is separate from the ipykernel package so we can avoid doing imports until
Out[13]:

Age group classification with scikit-learn

ConnectivityMeasure can be used to extract features for supervised learning

In [14]:
from sklearn.svm import LinearSVC
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_val_score

kinds = ['correlation', 'partial correlation', 'tangent']
groups = [pheno['Child_Adult'] for pheno in rest_data.phenotypic]
classes = LabelEncoder().fit_transform(groups)

cv = StratifiedShuffleSplit(n_splits=15, random_state=0, test_size=10)

correlations = ConnectivityMeasure(
    kind='correlation', vectorize=True).fit_transform(masked_data)

scores = cross_val_score(LinearSVC(), correlations, classes, cv=cv)
print(np.mean(scores))
0.9466666666666668
In [15]:
import seaborn as sns
sns.violinplot(scores)
sns.stripplot(scores, color='k')
Out[15]:
<matplotlib.axes._subplots.AxesSubplot at 0x7fc1b6136ba8>

More about connectivity with nilearn: https://nilearn.github.io/connectivity/index.html

More about the development dataset: Richardson et al. (2018). Development of the social brain from age three to twelve years.